
package com.platform.modules.wx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.HttpUtils;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.modules.sys.service.SysConfigService;
import com.platform.modules.wx.dao.WxMaUrlLinkDao;
import com.platform.modules.wx.entity.WxMaConfigEntity;
import com.platform.modules.wx.entity.WxMaUrlLinkEntity;
import com.platform.modules.wx.service.WxMaConfigService;
import com.platform.modules.wx.service.WxMaUrlLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Service实现类
 *
 * @author
 * @date 2024-02-23 15:54:15
 */
@Service("wxMaUrlLinkService")
public class WxMaUrlLinkServiceImpl extends ServiceImpl<WxMaUrlLinkDao, WxMaUrlLinkEntity> implements WxMaUrlLinkService {
    @Autowired
    private WxMaConfigService wxMaConfigService;

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private SysConfigService configService;

    @Override
    public List<WxMaUrlLinkEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.id");
        params.put("asc", false);
        Page<WxMaUrlLinkEntity> page = new Query<WxMaUrlLinkEntity>(params).getPage();
        return page.setRecords(baseMapper.selectWxMaUrlLinkPage(page, params));
    }

    @Override
    public boolean add(WxMaUrlLinkEntity wxMaUrlLink) {
        wxMaUrlLink.setAddTime(new Date());
        generateUrlLink(wxMaUrlLink);
        return this.save(wxMaUrlLink);
    }

    @Override
    public boolean update(WxMaUrlLinkEntity wxMaUrlLink) {
        wxMaUrlLink.setUpdateTime(new Date());
        generateUrlLink(wxMaUrlLink);
        return this.updateById(wxMaUrlLink);
    }

    @Override
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }


    void generateUrlLink(WxMaUrlLinkEntity wxMaUrlLink) {
        String token;
        try {
            token = getAccessToken();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("token获取失败");
        }

        String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + token;

        StringBuilder params = new StringBuilder();
        params.append("{");

        params.append("\"env_version\": ").append("\"" + wxMaUrlLink.getEnvVersion() + "\"");
        if(StringUtils.isNotBlank(wxMaUrlLink.getPath())){
            params.append(",").append("\"path\":").append("\"" + wxMaUrlLink.getPath() + "\"");
        }


        if(StringUtils.isNotBlank(wxMaUrlLink.getQuery())){
            params.append(",").append("\"query\":").append("\"" + wxMaUrlLink.getQuery() + "\"");
        }

        if(wxMaUrlLink.getExpireType() != null){
            params.append(",").append("\"expire_type\":").append(wxMaUrlLink.getExpireType());
            if(wxMaUrlLink.getExpireType() == 0){
                params.append(",").append("\"expire_time\":").append(wxMaUrlLink.getExpireTime());
            }else{
                params.append(",").append("\"expire_interval\":").append(wxMaUrlLink.getExpireInterval());
            }
        }





        params.append("}");


        try {
            String result =  HttpUtils.sendPost(url, params.toString());
            JSONObject resultObject = JSONObject.parseObject(result);
            wxMaUrlLink.setErrcode(resultObject.getString("errcode"));
            wxMaUrlLink.setErrmsg(resultObject.getString("errmsg"));
            wxMaUrlLink.setUrlLink(resultObject.getString("url_link"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("urlLink生成失败");
        }

    }

    String getAccessToken() throws Exception {

        if (jedisUtil.exists("wxMaUrlLinkToken")) {
            return jedisUtil.get("wxMaUrlLinkToken");
        }

        WxMaConfigEntity maConfigEntity = wxMaConfigService.getOne(new QueryWrapper<>(), false);

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&" +
                "appid=" + maConfigEntity.getAppId() + "&secret=" + maConfigEntity.getSecret();

        String result = HttpUtils.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String token = jsonObject.getString("access_token");
        jedisUtil.set("wxMaUrlLinkToken", token, 7200);
        return token;
    }

}
